from itsdangerous import TimedJSONWebSignatureSerializer
from comment.utils.const import SECRET_KEY,JWT_EXPIRY_SECOND
from flask import current_app
from comment.models.user import User
def generate_tokens(uid):
    '''
    根据已经登录的用户id生成token
    :param uid:登录后的用户id
    :return:
    '''
    #需要传两个参数，，参数一：密钥，参数二：会话即token的过期时间
    s = TimedJSONWebSignatureSerializer(secret_key=SECRET_KEY,expires_in=JWT_EXPIRY_SECOND)
    #生成token
    return s.dumps({'id':uid}).decode()
def verify_token(token_str):
    '''
    验证token，验证成功后，返回用户id
    :param token_str:要验证的token
    :return:
    '''
    s =TimedJSONWebSignatureSerializer(secret_key=SECRET_KEY)
    try:
        data = s.loads(token_str)#实质上是一个解密的过程
    except Exception as e:
        current_app.logger.info('token验证失败')
        return {'message':'token验证失败'}
    #如果token验证成功，还需要看当前用户状态是否正常
    user =User.query.filter(User.id==data['id']).first()
    if user and user.status !=0:
        return {'message':'数据库中的用户状态过期'}
    return {'id':user.id}